﻿using System;
using Resources;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.WEB.GIMS.Class;
using KPIS.GERP.Models.Class;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    public class PurchaseCheckAssetController : Controller
    {
        private string[] _basicIncludeSubclass = new[]
		    {
				"Committees.CommitteeType", "Committees.CommitteePosition", "Committees.CommitteeFunction", "Committees.Employee.Position" 
		    };

        private string[] _basicIncludeSubclassTwo = new[]
            {
                "CommitteeType", "CommitteePosition", "CommitteeFunction"
            };
        //
        // GET: /PurchaseCheckAsset/
        #region InventoryStockTaking

        public ActionResult Index()
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            //var models = service.SelectListInventoryStockTaking(0, "D");
            var models = service.SelectInventoryStockTaking(new InventoryStockTaking { RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus }, new[] { "Warehouse", "JobSite", "MasResourceType" }).ToList();
            return View(models);
        }

        public ActionResult Details(int id)
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            //var model = service.SelectListInventoryStockTaking(id, "D").FirstOrDefault();
            var model = service.SelectInventoryStockTaking(new InventoryStockTaking { RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus, StockTakingId = id }, new[] { "Warehouse", "JobSite", "MasResourceType" }).FirstOrDefault();
            if (model != null)
            {
                return View(model);
            }
            else 
            {
                return HttpNotFound();
            }
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Models.ICM.InventoryStockTaking model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
                    var id = service.InsertInventoryStockTaking(model, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("Details", new { id });
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            //var model = service.SelectListInventoryStockTaking(id, "D").FirstOrDefault();
            var model = service.SelectInventoryStockTaking(new InventoryStockTaking { RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus, StockTakingId = id }, new[] { "Warehouse", "JobSite", "MasResourceType" }).FirstOrDefault();
            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Edit(int id, Models.ICM.InventoryStockTaking model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
                    service.UpdateInventoryStockTaking(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
                service.DeleteInventoryStockTaking(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteInventoryStockTaking(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }
        #endregion


        #region InventoryStockTakingItem

        public ActionResult IndexInventoryStockTakingItem(int StockTakingId)
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            var model = service.SelectInventoryStockTaking(new InventoryStockTaking { StockTakingId = StockTakingId, RecordStatus = "!" + "D" }, new[] { "JobSite", "Warehouse", "MasResourceType" }).FirstOrDefault();
            if (model != null)
            {
                ViewBag.StockTakingId = StockTakingId;
                ViewBag.ResourceType = model.MasResourceType.Name;
            }
            return View();
        }

        public ActionResult CreateInventoryStockTakingItem(int StockTakingId, int ResItemId, int SumAmountStock)
        {
            ViewBag.StockTakingId = StockTakingId;
            ViewBag.ResItemId = ResItemId;
            ViewBag.SumAmountStock = SumAmountStock;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateInventoryStockTakingItem(InventoryStockTakingItem model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();

                    // Insert to IcmInventoryStockTakingItem Table
                    service.InsertInventoryStockTakingItem(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("IndexInventoryStockTakingItem", new { StockTakingId = model.StockTakingId });
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return View(model);
        }

        public ActionResult EditInventoryStockTakingItem(int StockTakingId, int ResItemId, int SumAmountStock)
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            ViewBag.StockTakingId = StockTakingId;
            ViewBag.ResItemId = ResItemId;
            ViewBag.SumAmountStock = SumAmountStock;
            var model = service.SelectInventoryStockTakingItem(new InventoryStockTakingItem { StockTakingId = StockTakingId, ResItemId = ResItemId, RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus }, null).FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditInventoryStockTakingItem(InventoryStockTakingItem model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();

                    // Update IcmInventoryStockTakingItem Table
                    service.UpdateInventoryStockTakingItem(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("IndexInventoryStockTakingItem", new { StockTakingId = model.StockTakingId });
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return View(model);
        }

        #endregion


        #region InventoryStockTakingCommittee
        
        public ActionResult IndexInventoryStockTakingCommittee(int StockTakingId)
        {
            // assume StockTakingId is GroupId
            ViewBag.StockTakingId = StockTakingId;

            var service = new CommitteeGroupService.CommitteeGroupServiceClient();
            //var model = service.Select(new CommitteeGroup
            //    {
            //        CommitteeGroupId = StockTakingId,
            //        RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus
            //    }, _basicIncludeSubclass).First().Committees.
            //    // ComFunctionId = 76  >>>  76 คือ คณะกรรมการตรวจนับ).ToList();
            //    Where(o => o.RecordStatus != "D" && o.ComFunctionId == 76).ToList();

            var model = service.Select(new CommitteeGroup
                {
                    CommitteeGroupId = StockTakingId,
                    RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus
                }, _basicIncludeSubclass).FirstOrDefault();
            
           model.Committees = model.Committees.Where(o => o.RecordStatus != "D" && o.ComFunctionId == 76).ToList();

           if (model.Committees == null)
            {
                return HttpNotFound();
            }

           return View(model.Committees);
        }

        public ActionResult CommitteeDetails(int id)
        {
            var service = new CommitteeService.CommitteeServiceClient();
            var model = service.Select(new Committee
            {
                CommitteeId = id
            }, _basicIncludeSubclassTwo).FirstOrDefault();
            return View(model);
        }

        public ActionResult CreateCommittee(int StockTakingId)
        {
            var model = new Committee();
            model.CommitteeGroupId = StockTakingId;
            // Obsolete
            //model.RefType = 22;
            model.ComTypeId = 8;
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateCommittee(Committee model, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new CommitteeService.CommitteeServiceClient();
                    var id = service.Insert(model, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("CommitteeDetails", new { id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View(model);
        }

        public ActionResult EditCommittee(int id)
        {
            var service = new CommitteeService.CommitteeServiceClient();
            var model = service.Select(new Committee { CommitteeId = id }, _basicIncludeSubclassTwo).FirstOrDefault();
            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditCommittee(int id, Committee model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new CommitteeService.CommitteeServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("CommitteeDetails", new { id });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult DeleteCommittee(int id, int StockTakingId)
        {
            try
            {
                var service = new CommitteeService.CommitteeServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);
                service.Close();
                return RedirectToAction("IndexInventoryStockTakingCommittee", new { StockTakingId = StockTakingId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteCommitteeAll(int[] deleteIds)
        {
            if (deleteIds == null)
                return Json(new { success = true });

            try
            {
                var service = new CommitteeService.CommitteeServiceClient();
                foreach (int delete in deleteIds)
                {
                    service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                }

                ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return Json(new { success = false });
            }
        }

        public ActionResult GetEmployeeDetails(int id)
        {
            var service = new EmployeeService.EmployeeServiceClient();
            var result = service.Select(new Models.HRM.Employee() { EmpId = id }, new[] { "Position", "JobSite" }, null).FirstOrDefault();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        // อนุมัติ
        public ActionResult Approved(int StockTakingId)
        {
            var service = new PurchaseCheckAssetService.PurchaseCheckAssetServiceClient();
            service.Approved(StockTakingId, Class.GimsMembership.CurrentEmpId);
            return RedirectToAction("Index");
        }
        #endregion
    }
}
